const http = require("http")
const session = {}
http
  .createServer((req, res) => {
    if (req.url === "/favicon.ico") {
      res.end("")
      return
    }
    // 观察cookie
    console.log("cookie", req.headers.cookie)
    //设置cookie
    // res.setHeader("Set-Cookie", "cookie1=123")
    // res.end("hello cookie")
    const sesssionKey = "sid"
    const cookie = req.headers.cookie

    if (cookie && cookie.indexOf(sesssionKey) > -1) {
      res.end("come back")
      const pattern = new RegExp(`${sesssionKey}=([^;]+);?\s*`)
      const sid = pattern.exec(cookie)[1]
      console.log("session", sid, session, session[sid])
    } else {
      const sid = (Math.random() * 99999).toFixed()
      //设置cookie
      res.setHeader("Set-Cookie", `${sesssionKey}=${sid}`)
      session[sid] = { fiest: "tests" }
      res.end("hello")
    }
  })
  .listen(9989, () => {
    console.log("ok")
  })
